package com.aistar.controller;

import com.aistar.model.bo.Result;
import com.aistar.model.entity.Employee;
import com.aistar.model.entity.Employer;
import com.aistar.model.entity.User;
import com.aistar.service.user.IRegisterService;
import com.aistar.service.user.IUserService;
import com.aistar.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/register")
public class RegisterRestController {
    @Autowired
    private IUserService userService;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private IRegisterService registerService;

    @PostMapping("/send")
    public Result send(HttpServletRequest request,String email){
        System.out.println(email);
        User u = userService.findByEmail(email);
        if (null!=u)
            return new Result("404","邮箱已注册!");
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom("2294014200@qq.com");
        msg.setSubject("欢迎您");//标题
        int n = (int) (Math.random()*90000+10000);

        //将这个验证码放入到session - 不能设置过期时间
        //以后放到redis,设置过期时间
        HttpSession session = request.getSession();
        session.setAttribute("code",String.valueOf(n));
//        request.setAttribute("code",String.valueOf(n));
        msg.setText("验证码:"+n);

        msg.setTo(email);//登录页面输入的 - 收件方
        //真正的发送
        mailSender.send(msg);
        return new Result("200","邮箱发送成功");
    }

//    @PostMapping("/email/code")
//    public Result emailCode(String email) {
//        Integer count = registerService.;
//        if (count == -1)
//            return new Result("501", "邮箱不存在");
//        else if (count == 1)
//            return new Result("200", "验证码发送成功");
//        return new Result("500", "很抱歉,请您重试");
//    }

    @PostMapping("/email")
    public Result Email(HttpServletRequest request, String email, String code,String password) {
        System.out.println(code);
        System.out.println(email);
        System.out.println(password);
        HttpSession session=request.getSession();
        String cod = (String) session.getAttribute("code");
        System.out.println(cod.equals(code));
        if (!cod.equals(code))
            return  new Result("404","验证码错误");
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        int count = userService.insterUser(user);
        if (count!=1)
            return new Result("500","注册失败");
        return new Result("200","注册成功");
    }
}
